package com.ruoyi.web.controller.teaching;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.teaching.domain.Option;
import com.ruoyi.teaching.domain.vo.PlatformQQuestionVO;
import com.ruoyi.teaching.service.CheckService;
import com.ruoyi.teaching.service.PlatformQQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 王旭
 * @since 2024-06-12
 */
@RestController
@RequestMapping("/platform/question")
@Api(tags = "platform-题库管理")
public class PlatformQQuestionController {
    @Autowired
    private PlatformQQuestionService platformQQuestionService;

    @Autowired
    private CheckService checkService;


    /**
     * 查询题库列表（题库页面）
     */
//    @PreAuthorize("@ss.hasPermi('platform:question:list')")
    @GetMapping("/listQuestion")
    @ApiOperation(value = "查询题库列表（题库页面）", notes = "查询题库列表（题库页面）")
    public AjaxResult listQuestion(Integer questionType, String questionName, Integer pageNum, Integer pageSize, Integer knowledgeId) {
        return platformQQuestionService.selectPlatformQQuestionListInQuestion(questionType, questionName, pageNum, pageSize, knowledgeId);
    }

    /**
     * 查询题库列表（发布页面）
     */
//    @PreAuthorize("@ss.hasPermi('platform:question:list')")
    @GetMapping("/listExam")
    @ApiOperation(value = "查询题库列表（发布页面）", notes = "查询题库列表（发布页面）")
    public AjaxResult listExam(Integer questionType, String questionName, Integer pageNum, Integer pageSize, String knowledgeName) {
        return platformQQuestionService.selectPlatformQQuestionListInExam(questionType, questionName, pageNum, pageSize, knowledgeName);
    }

    /**
     * 获取某些知识点下题目数量
     */
    @PostMapping(value = "/count")
    @ApiOperation(value = "获取某些知识点下题目数量", notes = "获取某些知识点下题目数量")
    public AjaxResult getCount(@RequestBody List<String> knowledgeNames) {
        return platformQQuestionService.getCount(knowledgeNames);
    }


    /**
     * 查询题目详细信息
     */
//    @PreAuthorize("@ss.hasPermi('platform:question:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "查询题目详细信息", notes = "查询题目详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return platformQQuestionService.selectPlatformQQuestionById(id);
    }

    /**
     * 新增题目
     */
    @Log(title = "【新增题目】", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增题目", notes = "新增题目")
    @PostMapping
    public AjaxResult add(@RequestBody List<PlatformQQuestionVO> platformQQuestionDTOs) {
        List<String> errorMessages = validatePlatformQQuestions(platformQQuestionDTOs);
        if (!errorMessages.isEmpty()) {
            return AjaxResult.error(String.join(", ", errorMessages));
        }
        return platformQQuestionService.insertPlatformQQuestion(platformQQuestionDTOs);
    }

    /**
     * 修改题目
     */
    @Log(title = "【修改题目】", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改题目", notes = "修改题目")
    @PutMapping
    public AjaxResult edit(@RequestBody PlatformQQuestionVO platformQQuestionDTO) {
        List<String> errorMessages = validatePlatformQQuestion(platformQQuestionDTO);
        if (!errorMessages.isEmpty()) {
            return AjaxResult.error(String.join(", ", errorMessages));
        }
        return platformQQuestionService.updatePlatformQQuestion(platformQQuestionDTO);
    }


    /**
     * 题目
     */
//    @PreAuthorize("@ss.hasPermi('platform:question:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除题目", notes = "删除题目")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            int i = id.intValue();
            String questionName = checkService.questionIsUse(i);
            if (!questionName.equals("")) {
                return AjaxResult.error("题目【 " + questionName + " 】已被使用，请重新选择后再进行删除");
            }
        }
        return platformQQuestionService.deletePlatformQQuestionByIds(ids);
    }

    /**
     * 验证一组 PlatformQQuestionVO 对象的题目选项和答案。
     *
     * @param platformQQuestions 要验证的 PlatformQQuestionVO 对象列表
     * @return 包含所有错误消息的列表
     */
    private List<String> validatePlatformQQuestions(List<PlatformQQuestionVO> platformQQuestions) {
        List<String> errorMessages = new ArrayList<>();
        for (PlatformQQuestionVO question : platformQQuestions) {
            errorMessages.addAll(validatePlatformQQuestion(question));
        }
        return errorMessages;
    }

    /**
     * 验证 PlatformQQuestionVO 对象的题目选项和答案。
     *
     * @param question 要验证的 PlatformQQuestionVO 对象
     * @return 包含所有错误消息的列表
     */
    private List<String> validatePlatformQQuestion(PlatformQQuestionVO question) {
        List<String> errorMessages = new ArrayList<>();
        String questionName = question.getQuestionName();

        // 验证题目是否为空以及长度是否在0-100之间
        if (questionName == null || questionName.isEmpty()) {
            errorMessages.add("有空题目，请检查后重试");
        } else if (questionName.length() > 100) {
            errorMessages.add("题目：" + questionName + " 的长度不能超过100个字符");
        }
        if (question.getQuestionType() == null) {
            errorMessages.add("题目：" + questionName + " 的题型不能为空");
        } else if (question.getQuestionType() < 0 || question.getQuestionType() > 4) {
            errorMessages.add("题目：" + questionName + " 的题型无效");
        }

        // 验证知识点id和题型是否为空
        if (question.getKnowledgeId() == null) {
            errorMessages.add("题目：" + questionName + " 的知识点不能为空");
        }
        //如果是填空题或简答题，将选项置为空数组
        else if (question.getQuestionType() == 3 || question.getQuestionType() == 4) {
            question.setOptions(new ArrayList<>());
        }

        // 如果题型为单选题、多选题、判断题，检查选项内容和图片
        if (question.getQuestionType() != null) {
            if (question.getQuestionType() == 0 || question.getQuestionType() == 1 || question.getQuestionType() == 2) {
                for (Option option : question.getOptions()) {
                    if ((option.getContent() == null || option.getContent().isEmpty()) && (option.getOptionImage() == null || option.getOptionImage().isEmpty())) {
                        errorMessages.add("题目：" + questionName + " 的选项 " + option.getOption() + " 的内容和图片不能同时为空");
                    }
                    if (option.getContent() != null && option.getContent().length() > 50) {
                        errorMessages.add("题目：" + questionName + " 的选项 " + option.getOption() + " 的内容长度不能超过50个字符");
                    }
                }
            }
        }

        // 根据题型验证答案
        if (question.getQuestionType() != null) {
            if (question.getQuestionType() == 1) { // 多选题
                validateMultipleChoiceAnswer(question, errorMessages);
            } else if (question.getQuestionType() == 3 || question.getQuestionType() == 4) { // 填空题或简答题
                validateTextualAnswer(question, errorMessages);
            } else { // 单选题或判断题
                validateSingleOrJudgeAnswer(question, errorMessages);
            }
        }
        return errorMessages;
    }

    static void validateMultipleChoiceAnswer(PlatformQQuestionVO question, List<String> errorMessages) {
        String questionName = question.getQuestionName();
        String[] questionAnswerMore = question.getQuestionAnswerMore();

        if (questionAnswerMore == null || questionAnswerMore.length == 0) {
            errorMessages.add("多选题：" + questionName + " 答案不能为空");
        } else {
            Set<String> validOptions = new HashSet<>(Arrays.asList("A", "B", "C", "D", "E", "F"));
            Set<String> answerSet = new HashSet<>(Arrays.asList(questionAnswerMore));

            if (!validOptions.containsAll(answerSet)) {
                errorMessages.add("多选题：" + questionName + " 答案必须包含在A, B, C, D, E, F中");
            }

            boolean optionEExists = question.getOptions().stream().anyMatch(o -> "E".equals(o.getOption()));
            boolean optionFExists = question.getOptions().stream().anyMatch(o -> "F".equals(o.getOption()));

            if (answerSet.contains("E") && !optionEExists) {
                errorMessages.add("多选题：" + questionName + " 答案不能包含E，因为选项E不存在");
            }
            if (answerSet.contains("F") && !optionFExists) {
                errorMessages.add("多选题：" + questionName + " 答案不能包含F，因为选项F不存在");
            }
            if (optionFExists && !optionEExists) {
                errorMessages.add("多选题：" + questionName + " 选项F存在时，选项E也必须存在");
            }
        }
    }

    private void validateTextualAnswer(PlatformQQuestionVO question, List<String> errorMessages) {
        String questionName = question.getQuestionName();
        String questionAnswer = question.getQuestionAnswer();

        if (questionAnswer == null || questionAnswer.isEmpty()) {
            errorMessages.add((question.getQuestionType() == 3 ? "填空题：" : "简答题：") + questionName + " 的答案不能为空");
        }
    }

    static void validateSingleOrJudgeAnswer(PlatformQQuestionVO question, List<String> errorMessages) {
        String questionName = question.getQuestionName();
        String questionAnswer = question.getQuestionAnswer();

        if (questionAnswer == null || questionAnswer.isEmpty()) {
            errorMessages.add("题目：" + questionName + " 的答案不能为空");
        } else {
            Set<String> validOptions = question.getQuestionType() == 0 ? new HashSet<>(Arrays.asList("A", "B", "C", "D")) : new HashSet<>(Arrays.asList("A", "B"));

            if (!validOptions.contains(questionAnswer)) {
                errorMessages.add("题目：" + questionName + " 的答案必须是 " + validOptions + " 中的一个");
            }
        }
    }

}

